package com.metadata_system.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

public class MyAesUtils {

    private static final String SECRET = "AES";
    public static final String KEY = "2nh1cqq1zpp7faf7";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";


    /**
     * AES加密(ECB模式, PKCS5Padding)
     * @param content 明文
     * @param key 密钥(AES-128:16字节, AES-192:24字节, AES-256:32字节)
     * @return Base64编码的密文
     */
    public static String encrypt(String content, String key) {
        try {
            // 转换密钥
            byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, SECRET);

            // 使用标准JDK提供的PKCS5Padding
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            // 加密
            byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));

            // Base64编码
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    /**
     * AES解密(ECB模式, PKCS5Padding)
     * @param content Base64编码的密文
     * @param key 密钥
     * @return 明文
     */
    public static String decrypt(String content, String key) {
        try {
            // 转换密钥
            byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, SECRET);

            // 使用标准JDK提供的PKCS5Padding
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            // Base64解码
            byte[] encrypted = Base64.getDecoder().decode(content);

            // 解密
            byte[] original = cipher.doFinal(encrypted);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }
}
